import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  name: '',
  roles: [],
}

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  login({
    commit
  }, userInfo) {
    const {
      account,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        account: account.trim(),
        password: password
      }).then(response => {
        const {
          token
        } = response.data;
        setToken('token', token);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo({}).then(response => {
        if (response.code != 200200) {
          return reject('认证失败，请重新登录')
        }
        const {
          name,
          role_code
        } = response.data;
        let roles = [role_code];
        commit('SET_NAME', name);
        commit('SET_ROLES', roles)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout({}).then(() => {
        removeToken('token')
        commit('SET_ROLES', [])
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken('token')
      commit('SET_ROLES', [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
